package state;

import state.util.array.ObjectArray;

public class KeyManagement implements KeyListener {
  private final int POOL_SIZE = 30;
  private ObjectArray keyListeners = ObjectArray.create(POOL_SIZE);

  private void expandSize() {
    ObjectArray tmp = ObjectArray.create(keyListeners.len() * 2);
    System.arraycopy(keyListeners, 0, tmp, 0, keyListeners.len());
    keyListeners = tmp;
  }
  
  public void addTarget(KeyListener keyListener) {
    // Check if this listener exist
    for (int i = 0; i < keyListeners.len(); i++) {
      if (keyListeners.get(i) == keyListener) {
        return;
      }
    }

    // Put this listener to list
    boolean isNotEnoughSpace = true;
    for (int i = 0; i < keyListeners.len(); i++) {
      if (keyListeners.get(i) == null) {
        keyListeners.set(i, keyListener);
        isNotEnoughSpace = false;
        break;
      }
    }
    
    if (isNotEnoughSpace) {
      expandSize();
      addTarget(keyListener);
    }
  }

  public void removeTarget(KeyListener keyListener) {
    for (int i = 0; i < keyListeners.len(); i++) {
      if (keyListeners.get(i) == keyListener) {
        keyListeners.set(i, null);
        break;
      }
    }
  }

  public void keyPressed(int keyCode) {
    for (int i = 0; i < keyListeners.len(); i++) {
      if (keyListeners.get(i) != null) {
        ((KeyListener) keyListeners.get(i)).keyPressed(keyCode);
      }
    }
  }

  public void keyReleased(int keyCode) {
    for (int i = 0; i < keyListeners.len(); i++) {
      if (keyListeners.get(i) != null) {
        ((KeyListener) keyListeners.get(i)).keyReleased(keyCode);
      }
    }
  }

  public void keyRepeated(int keyCode) {
    for (int i = 0; i < keyListeners.len(); i++) {
      if (keyListeners.get(i) != null) {
        ((KeyListener) keyListeners.get(i)).keyRepeated(keyCode);
      }
    }
  }
}
